<template>
  <!-- <el-affix :offset="0"> -->
  <el-card shadow="always">
    <template #header>
      <div class="card-header">
        <span>{{ t('log.title') }}</span>
        <el-button
          class="button"
          type="primary"
          @click="clearLog"
        >
          {{ t('log.clear') }}
        </el-button>
      </div>
    </template>

    <el-scrollbar
      ref="scrollbarRef"
      always
      noresize
      @scroll="scroll"
      :max-height="max"
    >
      <el-empty
        v-if="agvServerLog.length <= 0"
        :description="t('log.noLog')"
      />
      <div
        v-else
        ref="innerRef"
        v-for="(item, index) in agvServerLog"
        :key="index"
        class="scrollbar-item"
      >
        {{ item }}
      </div>
    </el-scrollbar>
  </el-card>
  <!-- </el-affix> -->
</template>

<script lang="ts" setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { ElScrollbar } from 'element-plus'
import { agvServerStore } from '@/store/agvServerStore'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'

let agvServerWatch = null

const { t } = useI18n()

const lineHeight = 20 // 每行高度
const maxNumber = 25 // 最大显示数量

const max = ref(0)
const store = agvServerStore()
const { agvServerLog } = storeToRefs(store)

const innerRef = ref<HTMLDivElement>()

const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()

onMounted(() => {
  max.value = maxNumber * lineHeight
  nextTick(() => {
    scrollbarRef.value!.setScrollTop(20 * agvServerLog.value.length)
  })

  startWatch()
})

const startWatch = () => {
  if (agvServerWatch === null) {
    agvServerWatch = watch(agvServerLog, (newValue, oldValue) => {
      if (agvServerLog.value.length > 0) {
        nextTick(() => {
          scrollbarRef.value!.setScrollTop(20 * newValue.length)
        })
      }
    }, {
      immediate: true,
      deep: true
    })
  }
}

const stopWatch = () => {
  if (agvServerWatch !== null) {
    agvServerWatch()
    agvServerWatch = null
  }
}

const clearLog = () => {
  localStorage.removeItem('agvServerLog')
  startWatch()
  agvServerLog.value = []
}

const scroll = ({ scrollTop }) => {
  if (scrollTop < 0) {
  } else if (scrollTop < (lineHeight * (agvServerLog.value.length - 3) - max.value)) {
    // 如果相差三行，取消监听
    stopWatch()
  } else if (scrollTop > (lineHeight * (agvServerLog.value.length - 1) - max.value) && scrollTop < (lineHeight * (agvServerLog.value.length + 1) - max.value)) {
    startWatch()
  }
}

</script>
<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.scrollbar-item {
  height: 20px;
  overflow: visible;
  white-space:nowrap;
  text-overflow: ellipsis;
}
</style>
